#!/usr/bin/env python
# coding=utf-8
import pretty_errors
import requests
import re

# 3.2.1 requests 基本用法
# 2.实例引入
r = requests.get('https://www.baidu.com')
print(type(r))
print(r.status_code)
print(type(r.text))
print(r.text)
print(r.cookies)

# 3.GET请求
r = requests.get('http://127.0.0.1:5000/get')  # 注意路径参数get不可遗漏
print('\n GET请求')
print(r.text)

# 带参数传入get,参数封装于字典中
data = {
    'name': 'mahayu',
    'age': 36,
}
r = requests.get('http://127.0.0.1:5000/get', params=data)  # 注意路径参数get不可遗漏
print('\n 带参数传入的get请求')
print(r.text)

# 返回结果构造为json的字典形式
r = requests.get('http://127.0.0.1:5000/get')
print(type(r.text))
print(r.json())
print(type(r.json()))

# 抓取网页---运行结果???P125
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) '
                  'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'
}
r = requests.get('https://www.zhihu.com/explore', headers=headers)
pattern = re.compile('explore-feed.*?question_link.*?>(.*?)</a>', re.S)
title = re.findall(pattern, r.text)
print(title)

# 抓取二进制数据
r = requests.get('https://github.com/favicon.ico')
print(r.text)
print(r.content)
with open('favicon.ico', 'wb') as f:
    f.write(r.content)

# 4.POST请求
data = {'name': 'joker', 'age': 58}
r = requests.post('http://127.0.0.1:5000/post', data=data)
print('\n post请求方式')
print(r.text)

# 5.响应
r = requests.get('http://www.jianshu.com')
print(type(r.status_code), r.status_code)
print(type(r.headers), r.headers)
print(type(r.cookies), r.cookies)
print(type(r.url), r.url)
print(type(r.history), r.history)
